package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.bean.CourseQuestionAnswerBean;
import com.atguigu.edu.realtime.bean.InteractionCourseCommentBean;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.MyClickhouseUtil;
import com.atguigu.edu.realtime.util.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;

import java.util.Collections;
import java.util.HashSet;
//卢顺祥 课程域问题粒度答题情况汇总表
public class DwsCourseQuestionAnswerWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1. 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment
                .createLocalEnvironmentWithWebUI(new Configuration());
        env.setParallelism(4);

        // TODO 2. 检查点相关设置(略)
        // TODO 3. 从 Kafka dwd_course_test_exam 主题读取课程数据
        String topic = "dwd_course_question_answer";
        String groupId = "dws_trade_province_order_window";

        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getKafkaConsumer(topic, groupId);
        DataStreamSource<String> source = env.addSource(kafkaConsumer);

        // TODO 4.转换数据结构
        SingleOutputStreamOperator<JSONObject> mappedStream = source.map(JSON::parseObject);
        //{"create_time":"2022-10-20 20:08:58","user_id":"26",
        // "id":"349442","date_id":"2022-10-20","question_id":"2587",
        // "is_correct":"0","ts":"1666267737"}

        // TODO 7. 转换数据结构
        SingleOutputStreamOperator<CourseQuestionAnswerBean> javaBeanStream = mappedStream.map(
                jsonObj -> {
                    String question_id = jsonObj.getString("question_id");
                    Double is_correct = jsonObj.getDouble("is_correct");
                    Long ts = jsonObj.getLong("ts") * 1000L;

                    CourseQuestionAnswerBean tradeProvinceOrderWindow = CourseQuestionAnswerBean.builder()
                            .questionId(question_id)
                            .answerCount(1L)
                            .orderIdSet(new HashSet<String>(
                                    Collections.singleton(question_id)
                            ))
                            .correctAmount(is_correct)
                            .ts(ts)
                            .build();
                    return tradeProvinceOrderWindow;
                }
        );
        //CourseQuestionAnswerBean(stt=null, edt=null, questionId=2467, answerCount=1, orderIdSet=[2467], correctAmount=0.0, ts=1666338859000)
        //javaBeanStream.print();


        // TODO 8. 设置水位线
        SingleOutputStreamOperator<CourseQuestionAnswerBean> withWatermarkStream = javaBeanStream.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<CourseQuestionAnswerBean>forMonotonousTimestamps()
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<CourseQuestionAnswerBean>() {
                                    @Override
                                    public long extractTimestamp(CourseQuestionAnswerBean javaBean, long recordTimestamp) {
                                        return javaBean.getTs();
                                    }
                                }
                        )
        );

        // TODO 9. 按照试卷 ID 分组
        KeyedStream<CourseQuestionAnswerBean, String> keyedByProIdStream =
                withWatermarkStream.keyBy(CourseQuestionAnswerBean::getQuestionId);

        // TODO 10. 开窗
        WindowedStream<CourseQuestionAnswerBean, String, TimeWindow> windowDS = keyedByProIdStream.window(TumblingEventTimeWindows.of(
                org.apache.flink.streaming.api.windowing.time.Time.seconds(10L)
        ));

        // TODO 11. 聚合计算
        SingleOutputStreamOperator<CourseQuestionAnswerBean> reducedStream = windowDS.reduce(
                new ReduceFunction<CourseQuestionAnswerBean>() {
                    @Override
                    public CourseQuestionAnswerBean reduce(CourseQuestionAnswerBean value1, CourseQuestionAnswerBean value2) throws Exception {
                        value1.getOrderIdSet().addAll(
                                value2.getOrderIdSet()
                        );
                        value1.setAnswerCount(
                                value1.getAnswerCount() + value2.getAnswerCount()
                        );
                        value1.setCorrectAmount(value1.getCorrectAmount()+value2.getCorrectAmount());
                        return value1;
                    }
                },
                new ProcessWindowFunction<CourseQuestionAnswerBean, CourseQuestionAnswerBean, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<CourseQuestionAnswerBean> elements, Collector<CourseQuestionAnswerBean> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(context.window().getStart());
                        String edt = DateFormatUtil.toYmdHms(context.window().getEnd());
                        for (CourseQuestionAnswerBean element : elements) {
                            element.setStt(stt);
                            element.setEdt(edt);
                            //element.setOrderCount((long) element.getOrderIdSet().size());
                            element.setTs(System.currentTimeMillis());
                            out.collect(element);
                        }
                    }
                }
        );
        reducedStream.print();
        SinkFunction<CourseQuestionAnswerBean> jdbcSink = MyClickhouseUtil.<CourseQuestionAnswerBean>getSinkFunction(
                "insert into Dws_Course_Question_Answer_Window values(?,?,?,?,?,?)"
        );
        reducedStream.<CourseQuestionAnswerBean>addSink(jdbcSink);


        env.execute();
    }
}
